package aos.maekawa.socket;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Queue;

import aos.maekawa.entity.Message;
import aos.maekawa.entity.ReportData;
import aos.maekawa.entity.RouteTable;
import aos.maekawa.exception.AosException;
import aos.maekawa.log.LogUtils;

public class SocketListener implements Runnable {
	private ServerSocket serverSocket;
	// private HashMap<Integer, SocketHandler> id2Socket;
	// private RouteTable routeTable;
	private Queue<Message> messageQueue;
	private ReportData report;

	public SocketListener(int port, HashMap<Integer, SocketHandler> id2Socket,
			RouteTable routeTable, Queue<Message> messageQueue,
			ReportData report) throws AosException {
		try {
			this.serverSocket = new ServerSocket(port);
		} catch (IOException e) {
			LogUtils.errorLog("server open socket failed, with port: " + port);
			LogUtils.errorLog(e.getMessage());
			throw new AosException(e.getMessage(), e);
		}
		// this.id2Socket = id2Socket;
		// this.routeTable = routeTable;
		this.messageQueue = messageQueue;
		this.report = report;
	}

	@Override
	public void run() {
		while (true) {
			Socket socket = null;
			SocketHandler socketHandler = null;
			try {
				socket = serverSocket.accept();
				socketHandler = new SocketHandler(socket, messageQueue, report);
			} catch (IOException e) {
				LogUtils.errorLog(e.getMessage());
				continue;
			}
			LogUtils.runLog("serverSocket accept, connect with "
					+ socket.getInetAddress().getHostAddress());
			// int id = -1;
			// try {
			// id = routeTable.getNodeIdByIp(socket.getInetAddress()
			// .getHostAddress());
			// id2Socket.put(id, socketHandler);
			// } catch (AosException e) {
			// LogUtils.errorLog("fatal error, iptable file may be wrongly configured: "
			// + socket.getInetAddress().getHostAddress());
			// LogUtils.errorLog(e.getMessage());
			// System.exit(-1);
			// }
			// LogUtils.runLog("socket cached, id: " + id + " address: "
			// + socket.getInetAddress().getHostAddress());
			new Thread(socketHandler).start();

		}
	}
}
